package com.noble.meether.ui.reg.mobile;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.noble.glamour.module.logic.application.App;
import com.noble.glamour.module.logic.application.ModuleMgr;
import com.noble.glamour.module.logic.baseui.LoadingDialog;
import com.noble.glamour.module.logic.config.UrlParam;
import com.noble.glamour.module.logic.request.HttpResponse;
import com.noble.glamour.module.logic.request.RequestComplete;
import com.noble.glamour.module.util.ChineseFilter;
import com.noble.glamour.module.util.CountDownTimer;
import com.noble.glamour.module.util.UIShow;
import com.noble.library.log.PToast;
import com.noble.library.third.ThirdConstant;
import com.noble.library.view.base.BaseDialogFragment;
import com.noble.meether.R;
import com.noble.meether.fragment.rob.util.RobClickListener;

/**
 * 手机验证码登录弹框
 */
public class RegMobileDlg extends BaseDialogFragment implements View.OnClickListener, RequestComplete, TextWatcher {
    private EditText edtPhone, edtCode;
    private TextView getCode;
    private ImageView btnClear;
    private String phone, code;

    public RegMobileDlg() {
        settWindowAnimations(R.style.AnimDownInDownOutOverShoot);
        setGravity(Gravity.CENTER);
        setDialogSizeRatio(0, 0);
        setCanceledOnTouchOutside(false);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        setContentView(R.layout.reg_mobile_dialog);
        initView();
        return getContentView();
    }

    private void initView() {
        edtPhone = (EditText) findViewById(R.id.login_mobile);
        edtCode = (EditText) findViewById(R.id.login_code);
        getCode = (TextView) findViewById(R.id.login_get_code);
        btnClear = (ImageView) findViewById(R.id.btn_clear);
        edtPhone.addTextChangedListener(this);
        btnClear.setOnClickListener(this);
        findViewById(R.id.btn_submit).setOnClickListener(this);
        findViewById(R.id.btn_close).setOnClickListener(this);
        getCode.setOnClickListener(new RobClickListener() {
            @Override
            public void onRobClick(View v) {
                if (validPhone()) {
                    ModuleMgr.getLoginMgr().reqSendCode(phone, RegMobileDlg.this);
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_submit:    // 手机号验证码登陆
                sendCode();
                break;
            case R.id.btn_close:
                dismiss();
                break;
            case R.id.btn_clear:
                edtPhone.setText("");
                break;
        }
    }

    private void sendCode() {
        code = edtCode.getText().toString();
        phone = edtPhone.getText().toString();
        if (!TextUtils.isEmpty(code)) {
            resetCountTime();
            LoadingDialog.show((FragmentActivity) App.getActivity(), "正在登录");
            ModuleMgr.getLoginMgr().reqVerifyCode(phone, code, this);
            return;
        }
        PToast.showShort("验证码错误，请重试");
    }

    private boolean validPhone() {
        phone = edtPhone.getText().toString();
        if ("".equals(phone)) {
            PToast.showShort("手机号码不能为空");
            return false;
        }
        if (!ChineseFilter.isPhoneNumber(phone)) {
            PToast.showShort("手机号格式不正确");
            return false;
        }
        return true;
    }

    @Override
    public void onRequestComplete(HttpResponse response) {
        PToast.showShort(response.getMsg());

        // 发送验证码
        if (response.getUrlParam() == UrlParam.reqSendCode) {
            if (response.isOk()) {
                startCountTime();
            }
            return;
        }

        // 手机验证码登录
        if (response.getUrlParam() == UrlParam.reqLogin) {
            ThirdConstant.Third_Avatar = "";
            ThirdConstant.Third_NickName = "";
            UIShow.showRegInfoAct((FragmentActivity) App.getActivity());
        }
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        int num = charSequence.toString().length();
        btnClear.setVisibility(num > 0 ? View.VISIBLE : View.GONE);
    }

    @Override
    public void afterTextChanged(Editable editable) {
    }

    // ==================================  倒计时  =========================================
    private CountDownTimer mDownTimer;

    private void startCountTime() {
        stopCountTime();
        getCode.setClickable(false);
        int countDownInterval = 1000;
        mDownTimer = new CountDownTimer(60 * 1000, countDownInterval) {
            @Override
            public void onTick(long millisUntilFinished) {
                getCode.setText(String.format("重新发送（%1$d）秒", millisUntilFinished / 1000));
            }

            @Override
            public void onFinish() {
                resetCountTime();
            }
        };
        mDownTimer.start();
    }

    private void resetCountTime() {
        stopCountTime();
        getCode.setText("获取验证码");
        getCode.setClickable(true);
    }

    private void stopCountTime() {
        if (mDownTimer != null)
            mDownTimer.cancel();
        mDownTimer = null;
    }
}

